package com.zmt.mrms.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

public class AdminInterceptor implements HandlerInterceptor {

	/***
	 * 在请求处理之前进行调用(Controller方法调用之前)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
//		System.out.println("执行了admin拦截器的preHandle方法");

		String requestUrl = request.getRequestURI();
		Cookie[] cookies = request.getCookies();
		String userId = null;
		String userRole = null;
		if (cookies != null) {
			for (Cookie cookie : cookies) {
				if (cookie.getName().equals("id")) {
					userId = cookie.getValue();
				} else if (cookie.getName().equals("role")) {
					userRole = cookie.getValue();
				}
			}
			if (!userRole.equals("ADMIN")) {
				if (userRole.equals("PATIENT")) {
					response.sendRedirect("/patient");
				} else if (userRole.equals("DOCTOR")) {
					response.sendRedirect("/doctor");
				} else {
					response.sendRedirect(request.getHeader("Referer"));
				}
				return false;
			} else {
				return true;
			}
		} else {
			response.sendRedirect("/admin/login");
			return false;
		}

	}

	/***
	 * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("执行了admin拦截器的postHandle方法");
	}

	/***
	 * 整个请求结束之后被调用，也就是在DispatchServlet渲染了对应的视图之后执行（主要用于进行资源清理工作）
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("执行了admin拦截器的afterCompletion方法");
	}
}
